package com.qinglian.handler;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.qinglian.exception.TokenAuthExpiredException;
import com.qinglian.utils.RedisUtil;
import com.qinglian.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        log.info("=======进入拦截器========");
        // 如果不是映射到方法直接通过,可以访问资源.
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        //为空就返回错误
        String token = httpServletRequest.getHeader("token");
        if (null == token || "".equals(token.trim())) {
            return false;
        }
        Integer userId = null;
        try {
            userId = tokenUtil.parseToken(token);
        } catch (RuntimeException e) {
            throw new TokenAuthExpiredException();
        }

        String redisToken = (String) redisUtil.get("token" + userId);
        if (token.equals(redisToken)) {
            return true;
        } else {
            throw new TokenAuthExpiredException();
        }
    }

}

